package com.fyy.im.server.handler;

import com.fyy.im.message.LoginRequestMessage;
import com.fyy.im.message.LoginResponseMessage;
import com.fyy.im.server.service.UserService;
import com.fyy.im.server.service.UserServiceFactory;
import com.fyy.im.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Author fyy
 * @Description
 * @Date 2021/5/12 9:43
 */
@ChannelHandler.Sharable
public class LoginMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {

        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username,password);
        LoginResponseMessage message;
        if(login){
            //记录用户与channel关联关系
            SessionFactory.getSession().bind(ctx.channel(),username);
            message = new LoginResponseMessage(true,"登录成功");
        }else{
            message = new LoginResponseMessage(false,"用户名密码错误");
        }
        ctx.writeAndFlush(message);

    }

}
